package deployr.httpclient;

import java.io.*;
import java.math.*;
import java.security.*;

public class Md5 {

	private static final String hex(byte[] array) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < array.length; ++i) {
			sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toLowerCase().substring(1, 3));
		}
		return sb.toString();
	}

	public static String md5(byte[] content) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			return hex(md.digest(content));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static final String md5(File file) {
		MessageDigest md5 = md5Digest();

		try {
			FileInputStream inputStream = openStreamOn(file);
			final byte[] buf = new byte[8192];
			int len;
			while ((len = inputStream.read(buf)) > 0) {
				md5.update(buf, 0, len);
			}
			inputStream.close();
			return new BigInteger(1, md5.digest()).toString(16);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static final String md5(String string) {
		try {
			return md5(string.getBytes("utf8"));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static MessageDigest md5Digest() {
		try {
			return MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static final FileInputStream openStreamOn(File file) throws FileNotFoundException {
		try {
			return new FileInputStream(file);
		} catch (Exception e) {
			throw new RuntimeException("unable to open stream " + file.getAbsolutePath(), e);
		}
	}
}
